﻿using DataWasher.WebApi.Entities;
using DataWasher.WebApi.EntitiesSQLServer;
using DataWasher.WebApi.IServices;
using DataWasher.WebApi.Models;
using DataWasher.WebApi.Repositories;
using DataWasher.WebApi.SqlServerRepositories;
using Microsoft.Azure.Cosmos.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ToolManager.Entities;
using ToolManager.IService;

namespace DataWasher.WebApi.Services
{
    public class ExtrackDataFromSqlServer : IExtrackDataFromSqlServer
    {
        private readonly IStoreInfoRepository _storeRepository;
        private readonly IBaseStoreBrandRepository _mysqlStoreRepository;
        private readonly IDomainRepository _domainRepository;
        public readonly IStorageService _storageService;
        public ExtrackDataFromSqlServer(IStoreInfoRepository storeRepository,
            IBaseStoreBrandRepository mysqlRepository,
            IDomainRepository domainRepository,
            IStorageService storageService)
        {
            _storeRepository = storeRepository;
            _mysqlStoreRepository = mysqlRepository;
            _domainRepository = domainRepository;
            _storageService = storageService;
        }
        /// <summary>
        /// 提取品牌信息到mysql
        /// </summary>
        /// <returns></returns>
        public async Task<bool> InsertToMysql()
        {
            try
            {
                //先清空表
                var entities = await _mysqlStoreRepository.GetAllAsync();
                await _mysqlStoreRepository.RemoveRangeAsync(entities);

                //插入从sqlserver同步过来的店铺和品牌信息
                var insertDatas = new List<SysBasestorebrand>();
                var dataSources = await _storeRepository.GetSourceDataPaged();
                dataSources.ForEach(d =>
                {
                    insertDatas.Add(new SysBasestorebrand()
                    {
                        Id = Guid.NewGuid().ToString().ToLower(),
                        BrandNameCn = d.BrandNameCN,
                        DomainId = d.DomainId,
                        DomainName = d.DomainName,
                        DomainTag = d.DomainTag,
                        Market = d.Market,
                        ParentDomainId = d.ParentDomainId,
                        StoreId = d.StoreId,
                        StoreName = d.StoreName,
                        TypeName = d.TypeName,
                        TagName = d.TagName
                    });

                });
                await _mysqlStoreRepository.AddRangeAsync(insertDatas);
                return true;


            }
            catch (Exception ex)
            {

                throw ex;
            }

            return false;
        }

        /// <summary>
        /// No used
        /// </summary>
        /// <returns></returns>
        public async Task<bool> InsertToStorage()
        {
            try
            {
                //插入前先删除
                await _storageService.DeleteTableAsync("DomainInfo");
                //等待storage table中的数据删除
                System.Threading.Thread.Sleep(60 * 1000);
                //获取sqlserver中domaininfo中的所有数据
                var sqlEntities = await _domainRepository.GetAllAsync();

                //去除已经标记为删除的记录
                sqlEntities = sqlEntities.Where(x => x.IsDeleted == false);
                var partitionKey = DateTime.Now.ToString("yyyyMM");

                //分页处理
                var sqlserverEntityList = new List<SysDomain>();
                var count = sqlEntities.Count();
                var pages = (count / 100) + 1;
                TableBatchOperation tableBatchOperation = null;
                DomainInfoEntity domainEntity = null;
                for (int index = 0; index < pages; index++)
                {
                    tableBatchOperation = new TableBatchOperation();
                    sqlserverEntityList = sqlEntities.Skip(index * 100).Take(100).ToList();
                    sqlserverEntityList.ForEach(e =>
                    {
                        domainEntity = new DomainInfoEntity(partitionKey)
                        {
                            DomainCode = e.DomainCode.ToString().ToLower(),
                            DomainId = e.DomainId.ToString().ToLower(),
                            DomainName = e.DomainName,
                            DomainTage = e.DomainTag,
                            OwnerId = e.OwnerId.ToString().ToLower(),
                            Owner = e.Owner.ToString().ToLower(),
                            ParentDomainId = e.ParentDomainId.ToString().ToLower()
                        };
                        tableBatchOperation.InsertOrReplace(domainEntity);
                    });
                    await _storageService.InsertBatchData(tableBatchOperation, "DomainInfo");
                }

                return true;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

    

    }
}

